<?php
class inman_api_cart{
	public function __construct($app){
		$this->app=$app;
		$this->cartModel=kernel::single('b2c_mdl_cart_objects');
		$this->goodsModel=kernel::single('b2c_mdl_goods');
		$this->productsModel=kernel::single('b2c_mdl_products');
		$this->memberModel=kernel::single('b2c_mdl_members');
	}
	//购物车列表
	public function getList($params,&$service){
		if(isset($params['sid'])&&$params['sid']!=null){
			$member_id=$this->check_sid($params['sid']);
			if(!$member_id){
           	 	return $service->send_user_error('100001','sid fail');
        	}else{
        		//根据ec原有的接口获取数据
        		$mCart = app::get('b2c')->model('cart');
        		$aCart = $mCart->get_objects($aData);
        		//商品
        		$result['object']['goods'] = $this->_get_cart_goods_data($aCart['object']['goods'],$aCart['promotion']['goods']);
        		//赠品
        		$result['object']['gift'] = $this->_get_cart_gift_data($aCart['object']['gift']);
        		//return $result['object']['gift'];
        		if(!$result['object']['goods']){
        			$error['status']='false';
					$error['message']=$this->app->_('购物车暂无数据');
					return $error;
        		}
        		//获取商品信息
        		foreach ($result['object']['goods'] as $key => $value) {
        			$product=$this->productsModel->getRow('product_id,goods_id,bn,marketable',array('product_id'=>$value['product_id']));
        			$good=$this->goodsModel->getRow('*',array('goods_id'=>$product['goods_id']));
        			//组装数据
        			$data[$key]['cart_id']=$value['obj_ident'];
        			$data[$key]['goods_sn']=$good['bn'];//$cart['params']['product_id']
        			$data[$key]['goods_name']=$value['name'];
        			$data[$key]['color_code']='未知';
        			$data[$key]['color_name']=$this->getColorByProductId($value['product_id']);
        			//只是返回XX、M、L这种类型的尺码
        			$data[$key]['size_name']=$this->getSizeByProductId($value['product_id']);
        			$data[$key]['sku_sn']=$product['bn'];
        			$data[$key]['shop_price']=$value['price'];
        			$data[$key]['transaction_price']=round((float)($value['total_price']/$value['quantity']),3);//成交价格
        			$data[$key]['img_url']=$value['pic'];
        			$data[$key]['goods_number']=$value['quantity'];//购买数量
        			//待确认，商品的可用库存，还是当前用户能够够买的库存
        			$data[$key]['available_number']=$value['store_real'];//可用库存(库存-冻结库存)
        			$data[$key]['is_on_sell']=$product['marketable'];//是否上架
        		}
        		//获取赠品信息
        		if($result['object']['gift']){
        			foreach ($result['object']['gift']['cart'] as $key=>$value ){
        				$product=$this->productsModel->getRow('product_id,goods_id,bn,marketable,store,freez',array('product_id'=>$value['product_id']));
        				$good=$this->goodsModel->getRow('*',array('goods_id'=>$product['goods_id']));
        				//组装数据
        				$gift[$key]['cart_id']=$value['obj_ident'];
        				$gift[$key]['goods_sn']=$good['bn'];//$cart['params']['product_id']
        				$gift[$key]['goods_name']=$value['name'];
        				$gift[$key]['color_code']='未知';
        				$gift[$key]['color_name']=$this->getColorByProductId($value['product_id']);
        				//只是返回XX、M、L这种类型的尺码
        				$gift[$key]['size_name']=$this->getSizeByProductId($value['product_id']);
        				$gift[$key]['sku_sn']=$product['bn'];
        				$gift[$key]['shop_price']=$value['price'];
        				$gift[$key]['transaction_price']='赠品价格？？';//成交价格
        				$gift[$key]['img_url']=$value['pic'];
        				$gift[$key]['goods_number']=$value['quantity'];//购买数量
        				$gift[$key]['available_number']=$product['store']-$product['freez'];//可用库存(库存-冻结库存):$product['store']-$product['freez']
        				$gift[$key]['is_on_sell']=$product['marketable'];//是否上架
        			}
        		}
        		
        		$return['cart_list']=array_merge($data,$gift);
        		return $return;
        	}

		}
		
	}
	//添加商品到购物车(赠品不能添加到购物车)
	public function add($params,&$service){
		//过滤特殊字符
		$obj_filter = kernel::single('b2c_site_filter');
        $params = $obj_filter->check_input($params);
        //验证用户身份
		if(isset($params['sid'])&&$params['sid']!=null){
			$member_id=$this->check_sid($params['sid']);
			if(!$member_id){
				$return['error_code']=1;return $return;//失败返回1
           	 	//return $service->send_user_error('100001','sid fail');
        	}else{
        		if(!isset($params['sku_sn'])||!isset($params['goods_number'])){
        			$return['error_code']=1;return $return;//失败返回1
 
        		}
        		$number=intval($params['goods_number']);
        		//检测数量是否正确
        		if($number<=0){
        			$return['error_code']=1;return $return;//失败返回1

        		}
        		//检测货品是否存在
        		$product=$this->productsModel->getRow('*',array('bn'=>$params['sku_sn']));
        		if(!$product){	
        			$return['error_code']=1;return $return;//失败返回1
        		}
        		//商品id、货品的id
		        $product=$this->productsModel->getRow('product_id,goods_id',array('bn'=>$params['sku_sn']));       
		        $data['goods']['goods_id'] = intval($product['goods_id']);
		        $data['goods']['product_id'] = intval($product['product_id']);
		        $data['goods']['num'] = $number;
		        $data[0] = 'gift';
		        $type = $data[0];//加入购物车商品类型，goods商品	gift 赠品 默认goods
        		/**
		         * 处理信息和验证过程
		         * servicelist('b2c_cart_object_apps')=>
		         * gift_cart_object_gift
		         * b2c_cart_object_coupon
		         * b2c_cart_object_goods
		         */
        		//获取检测的对象类
		        $arr_objects = array();
		        if ($objs = kernel::servicelist('b2c_cart_object_apps'))
		        {
		            foreach ($objs as $obj)
		            {
		                if ($obj->need_validate_store()){
		                    $arr_objects[$obj->get_type()] = $obj;
		                }
		            }
		        }
		        // $arr_objects['goods'] = $obj;
		        //$arr_objects['coupon'] = $obj;
		        //$obj等于class b2c_cart_object_coupon和class b2c_cart_object_goods
		       
		        
		        if (method_exists($arr_objects[$type], 'get_data'))
		        {
		            if (!$aData = $arr_objects[$type]->get_data($data,$msg))
		            {
		            	$return['error_code']=1;return $return;//失败返回1
		                // $error['status'] = 'false';
		                // $error['message'] = $msg;
		                // return $error;
		            }
		        }
		        // 进行各自的特殊校验
		        if (method_exists($arr_objects[$type], 'check_object'))
		        {
		            if (!$arr_objects[$type]->check_object($aData,$msg))
		            {
		            	$return['error_code']=1;return $return;//失败返回1
		                // $error['status'] = 'false';
		                // $error['message'] = $msg;
		                // return $error;
		            }
		        }
		        //检测库存
		        $obj_cart_object = kernel::single('b2c_cart_objects');
		        if (!$obj_cart_object->check_store($arr_objects[$type], $aData, $msg))
		        {
		        	$return['error_code']=1;return $return;//失败返回1
		            // $error['status'] = 'false';
		            // $error['message'] = $msg;
		            // return $error;
		        }

		        $obj_ident = $obj_cart_object->add_object($arr_objects[$type], $aData, $msg);
		        // $return['status'] = $obj_ident ? 'true' : 'false';
		        // $return['message'] = $msg;
		        $return['error_code']=$obj_ident ? 0 : 1;
		        return $return;
		        		
		    }
        }else{
        	//参数错误
        	$return['error_code']=1;
        	return $return;
 	    }
	}
	//更新购物车商品（goods_number代表更新到某个数目，不能为负数）
	public function update($params,&$service){
		//过滤特殊字符
		$obj_filter = kernel::single('b2c_site_filter');
        $params = $obj_filter->check_input($params);
        //验证用户身份
		if(isset($params['sid'])&&$params['sid']!=null){
			$member_id=$this->check_sid($params['sid']);
			if(!$member_id){
				$return['error_code']=1;return $return;//失败返回1
           	 	//return $service->send_user_error('100001','sid fail');
        	}else{
        		if(!isset($params['sku_sn'])||!isset($params['goods_number'])){
        			$return['error_code']=1;return $return;//失败返回1
        			//$error['status']='false';
					// $error['message']=$this->app->_('参数不正确');
					// return $error;
        		}
        		$number=intval($params['goods_number']);
        		//检测数量是否正确
        		if($number<=0){
        			$return['error_code']=1;return $return;//失败返回1
    				//$error['status']='false';
					// $error['message']=$this->app->_('goods_number不正确');
					// return $error;
        		}
        		//检测货品是否存在
        		$product=$this->productsModel->getRow('*',array('bn'=>$params['sku_sn']));
        		if(!$product){	
        			$return['error_code']=1;return $return;//失败返回1
					// $error['status']='false';
					// $error['message']=$this->app->_('sku_sn不正确');
					//return $error;
        		}
        		//商品id、货品的id
		        $product=$this->productsModel->getRow('product_id,goods_id',array('bn'=>$params['sku_sn']));       
		        $data['goods']['goods_id'] = intval($product['goods_id']);
		        $data['goods']['product_id'] = intval($product['product_id']);
		        $data['goods']['num'] = $number;
		        $data[0] = 'goods';
		        $type = $data[0];//加入购物车商品类型，goods商品	gift 赠品 默认goods
		        //购物车表的字段obj_ident
        		$obj_ident = $type.'_'.$data['goods']['goods_id'].'_'.$data['goods']['product_id'];
		        $arr_object['quantity'] = $number;
		        $mCartObject = app::get('b2c')->model('cart_objects');
		        //return $arr_object;
		        $_flag = $mCartObject->update_object($type,$obj_ident,$arr_object );
		       	if($_flag){
		       		$return['error_code']=0;
		       		return $return;
		       	}else{
		       		$return['error_code']=1;
		       		return $return;
		       	}
		        		
		    }
        }else{
        	//参数错误
        	$return['error_code']=1;
        	return $return;
        }
	}
	//删除购物车商品
	public function delete($params,&$service){
		//过滤特殊字符
		$obj_filter = kernel::single('b2c_site_filter');
        $params = $obj_filter->check_input($params);
        //验证用户身份
		if(isset($params['sid'])&&$params['sid']!=null){
			$member_id=$this->check_sid($params['sid']);
			if(!$member_id){
				$return['error_code']=1;return $return;//失败返回1
           	 	//return $service->send_user_error('100001','sid fail');
        	}else{
        		if(!isset($params['sku_sn'])||$params['sku_sn']==null){
        			$return['error_code']=1;return $return;//失败返回1
        			//$error['status']='false';
					// $error['message']=$this->app->_('参数不正确');
					// return $error;
        		}
        		//检测货品是否存在
        		$product=$this->productsModel->getRow('*',array('bn'=>$params['sku_sn']));
        		if(!$product){	
        			$return['error_code']=1;return $return;//失败返回1
					// $error['status']='false';
					// $error['message']=$this->app->_('sku_sn不正确');
					//return $error;
        		}
        		//商品id、货品的id
		        $product=$this->productsModel->getRow('product_id,goods_id',array('bn'=>$params['sku_sn']));
		        $data['goods']['goods_id'] = intval($product['goods_id']);
		        $data['goods']['product_id'] = intval($product['product_id']);
		        $data['goods']['num'] = $number;
		        $data[0] = 'goods';
		        $type = $data[0];//加入购物车商品类型，goods商品	gift 赠品 默认goods
		        $obj_ident = $type.'_'.$data['goods']['goods_id'].'_'.$data['goods']['product_id'];
		        $mCartObject = app::get('b2c')->model('cart_objects');
	            $flag = $mCartObject->remove_object($type, $obj_ident, $msg);
	            if($flag){
	            	$return['error_code']=0;
	            	return $return;
	            }else{
	            	$return['error_code']=1;
	            	return $return;
	            }

        	}
        }else{
        	//参数错误
        	$return['error_code']=1;
        	return $return;
        }
	}
	 private function set_sid($member_id){
        kernel::single("base_session")->start();
        $member_ident = kernel::single("base_session")->sess_id();
        $sess_id = md5($member_ident.'api'.$member_id);
        kernel::single("base_session")->set_sess_id($sess_id);
        return $sess_id;
    }

    private function check_sid($accesstoken){
        $_GET['sess_id'] = $accesstoken;
        kernel::single("base_session")->start();
        $userObject = kernel::single('b2c_user_object');
        $id = $userObject->get_member_id();
        if($id){
        	return $id;
        }else{
        	return false;
        }
    }
    //根据货品id获取颜色名称、编码
    private function getColorByProductId($id){
    	$product=$this->productsModel->getRow('*',array('product_id'=>$id));
    	$colors=$this->getAllSpecs('颜色');
    	if(!$colors){
    		return ;
    	}
    	if($product['spec_desc']){
        		//颜色\、尺寸规格
        		foreach ($product['spec_desc']['spec_value_id'] as $value) {
        			if(in_array($value, $colors)){
        				$name=kernel::single('b2c_mdl_spec_values')->getRow('spec_value',array('spec_value_id'=>$value));
        				return $name['spec_value'];
        			}
        		}
        }else{
        		return ;
        }
    }
    //根据货品id获取尺寸名称、编码
    private function getSizeByProductId($id){
    	$product=$this->productsModel->getRow('*',array('product_id'=>$id));
    	$sizes=$this->getAllSpecs('尺码');
    	if(!$sizes){
    		return ;
    	}
    	if($product['spec_desc']){
        		//颜色\、尺寸规格
        		foreach ($product['spec_desc']['spec_value_id'] as $value) {
        			if(in_array($value, $sizes)){
        				$name=kernel::single('b2c_mdl_spec_values')->getRow('spec_value',array('spec_value_id'=>$value));
        				return $name['spec_value'];
        			}
        		}
        }else{
        		return ;
        }
    }
    //获得指定规格的所有属性值(默认属性为‘颜色’)
    public function getAllSpecs($name='颜色'){
    	$spec_value_ids=kernel::single('b2c_mdl_specification')->getRow('spec_id',array('spec_name'=>$name));
    	if(!$spec_value_ids){
    		return ;
    	}
    	$spec_type_id=$spec_value_ids['spec_id'];
    	$specs=kernel::single('b2c_mdl_spec_values')->getList('spec_value_id',array('spec_id'=>$spec_type_id));
    	if(!$specs){
    		return ;
    	}
    	return $this->changeArr($specs);
    }
    private function changeArr($arrs){
    	if(is_array($arrs)){
    		foreach ($arrs as $arr) {
    			foreach ($arr as $item) {
    				$return[]=$item;
    			}
    		}
    		return $return;
    	}else{
    		return $arrs;
    	}
    }
    private function _get_cart_gift_data($cartGiftData){
        if( empty($cartGiftData) ) return array();
        $storager = kernel::single('base_storager');
        //积分兑换赠品数据
        if( $cartGiftData['cart'] ){
            foreach( $cartGiftData['cart'] as $i=>$giftRow ){
                $giftData[$i]['obj_ident'] = $giftRow['obj_ident'];
                $giftData[$i]['obj_type'] = $giftRow['obj_type'];

                $giftData[$i]['goods_id'] = $giftRow['goods_id'];
                $giftData[$i]['product_id'] = $giftRow['product_id'];
                $giftData[$i]['name'] = $giftRow['name'];
                $giftData[$i]['spec_info'] = $giftRow['spec_info'];
                $giftData[$i]['store_real'] = $giftRow['params']['real'];
                $giftData[$i]['quantity'] = $giftRow['quantity'];
                $giftData[$i]['price'] = $giftRow['price']['price'];
                $giftData[$i]['consume_score'] = $giftRow['consume_score'];
                $giftData[$i]['pic'] = $giftRow['thumbnail'] ? $giftRow['thumbnail'] : $giftRow['default_image']['thumbnail'];
                if( !strpos($giftData[$i]['pic'] ,'://')){
                    $giftData[$i]['pic'] = $storager->image_path($objectGoods[$i]['pic'],'m');
                }
            }
        }
        $return['cart'] = $giftData;

        if( $cartGiftData['order'] ){
            foreach( $cartGiftData['order'] as $i=>$giftRow ){
                $orderGiftData[$i]['goods_id'] = $giftRow['goods_id'];
                $orderGiftData[$i]['product_id'] = $giftRow['product_id'];
                $orderGiftData[$i]['name'] = $giftRow['name'];
                $orderGiftData[$i]['spec_info'] = $giftRow['spec_info'];
                $orderGiftData[$i]['quantity'] = $giftRow['quantity'];
                $orderGiftData[$i]['price'] = $giftRow['price']['price'];
                $orderGiftData[$i]['pic'] = $giftRow['thumbnail'] ? $giftRow['thumbnail'] : $giftRow['default_image']['thumbnail'];
                if( !strpos($orderGiftData[$i]['pic'] ,'://')){
                    $orderGiftData[$i]['pic'] = $storager->image_path($objectGoods[$i]['pic'],'m');
                }
            }
        }
        $return['order'] = $orderGiftData;
        return $return;
    }
    private function _get_cart_goods_data($goodsCart,$goodsPromotion){
        if( empty($goodsCart) ) return array();

        $storager = kernel::single('base_storager');
        foreach((array)$goodsCart as $i=>$goods ){
            $objectGoods[$i]['obj_ident'] = $goods['obj_ident'];
            $objectGoods[$i]['obj_type'] = $goods['obj_type'];

            $products = $goods['obj_items']['products'][0];
            $objectGoods[$i]['goods_id'] = $products['goods_id'];
            $objectGoods[$i]['product_id'] = $products['product_id'];
            $objectGoods[$i]['name'] = $products['name'];
            $objectGoods[$i]['spec_info'] = $products['spec_info'];
            $objectGoods[$i]['store_real'] = $goods['store']['real'];
            $objectGoods[$i]['quantity'] = $goods['quantity'];
            $objectGoods[$i]['price'] = $products['price']['price'];
            $discount_price = $goods['discount_amount_prefilter']+(($products['price']['price']-$products['price']['member_lv_price'])*$goods['quantity']);
            $objectGoods[$i]['discount_price'] = $discount_price;
            $objectGoods[$i]['total_price'] = $goods['subtotal_prefilter_after'];
            $objectGoods[$i]['score'] = $goods['subtotal_gain_score '] - $goods['subtotal_consume_score'];
            $objectGoods[$i]['pic'] = $products['thumbnail'] ? $products['thumbnail'] : $products['default_image']['thumbnail'];
            $objectGoods[$i]['pic'] = $storager->image_path($objectGoods[$i]['pic'],'m');

            //商品送赠品
            foreach( (array)$goods['gift'] as $k=>$gift ){
                $goods_promotion_gift[$k]['name'] = $gift['name'];
                $goods_promotion_gift[$k]['product_id'] = $gift['product_id'];
                $goods_promotion_gift[$k]['spec_info'] = $gift['spec_info'];
                $goods_promotion_gift[$k]['price'] = $gift['price']['price'] * $gift['quantity'];
                $goods_promotion_gift[$k]['quantity'] = $gift['quantity'];
            }
            $objectGoods[$i]['gift'] = $goods_promotion_gift;

            //商品促销
            if( $goodsPromotion[$goods['obj_ident']] ){
                foreach( (array)$goodsPromotion[$goods['obj_ident']] as $key=>$promotionRow ){
                    $promotionData[$key]['name'] = $promotionRow['name'];
                    $promotionData[$key]['tag'] = $promotionRow['desc_tag'];
                }
            }
            $objectGoods[$i]['promotion'] = $promotionData;
        }
        return $objectGoods;
    }
}